package com.yonyougov.devops.cruxcisupport;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yonyougov.devops.cruxcisupport.component.UserStore;
import com.yonyougov.devops.cruxcisupport.constvar.DevOpsErrorCode;
import com.yonyougov.devops.cruxcisupport.user.UserDao;
import com.yonyougov.devops.cruxcisupport.user.UserEntity;
import com.yonyougov.devops.cruxcisupport.util.Common;
import com.yonyougov.devops.fwc.api.dto.BaseResponseDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigInteger;

/**
 *
 */
@Component
@Slf4j
public class UpdatePassWordInterceptor implements HandlerInterceptor {
    private final UserStore userStore;
    private final UserDao userDao;
    private final ObjectMapper objectMapper;
    public static String[] ignoreUrls = new String[]{"^[http,https].*login.*", "^[http,https].*/u/add.*",
            "^[http,https].*/u/update.*","^[http,https].*/env/e/names.*",
            "^[http,https].*swagger.*", "^[http,https].*deployFile.*", "^[http,https].*configMap.*",
            "^[http,https].*downloadall.*", "^[http,https].*download",
            "^[http,https].*cluster.*", "^[http,https].*appenvport/aep/serverInfo", "^[http,https].*/server/u/status",
            "^[http,https].*/env/query", "^[http,https].*/encrypt", "^[http,https].*/decrypt"
            //,"^[http,https].*/harbor.*"
    };

    public UpdatePassWordInterceptor(UserStore userStore, UserDao userDao, ObjectMapper objectMapper) {
        this.userStore = userStore;
        this.userDao = userDao;
        this.objectMapper = objectMapper;
    }

    private boolean skip(HttpServletRequest request) {
        String url = request.getRequestURL().toString();
        for (String ignoreUrl : ignoreUrls) {
            if (url.matches(ignoreUrl)) {
                log.debug("跳过登录验证:{}", url);
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.debug("开始访问接口:{}", request.getRequestURI());
        if (skip(request)) {
            log.debug("接口:{}不需要认证跳过", request.getRequestURI());
            return true;
        }
        BigInteger userId = userStore.getCurrentUser().getId();
        UserEntity userEntity = userDao.findByPrimaryKey(userId);
        String password = userEntity.getPassword();
        if (password.equals(DigestUtils.md5DigestAsHex(Common.INITIAL_PASSWORD.getBytes()))) {
            log.error("密码是初始密码");
            response.setStatus(506);
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            BaseResponseDto errorResponseDto = BaseResponseDto.getFailInstance(DevOpsErrorCode.PASSWORD_INVALID);
            errorResponseDto.put(Common.NEED_EDIT_PASSWD, true);
            errorResponseDto.put(Common.USER_ID,userId);
            errorResponseDto.setErrorMsg("当前密码是初始密码");
            objectMapper.writeValue(response.getWriter(), errorResponseDto);
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
